<template>
   <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
         <el-form-item label="系统" prop="systemId">
            <el-select
               v-model="queryParams.systemId"
               placeholder="请选择所属系统"
               clearable
               style="width: 200px"
               @change="handleSystemChange('list')">
               <el-option
                  v-for="system in dataSystemOptions"
                  :key="system.id"
                  :label="system.name"
                  :value="system.id"
               />
            </el-select>
         </el-form-item>
         <el-form-item label="关键字" prop="keyword">
            <el-input v-model="queryParams.keyword" placeholder="请输入关键字" clearable style="width: 200px"
               @keyup.enter="handleQuery" />
         </el-form-item>
         <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
         </el-form-item>
      </el-form>

      <div style="display: flex">
         <div>
            <div class="tree-title">字典类型</div>
            <el-tree
               :data="dictTypeOptions"
               :props="{ label: 'typeName' }"
               @node-click="handleDictTypeClick"
            />
         </div>
         <div style="flex: 1">
            <el-row :gutter="10" class="mb8">
               <el-col :span="1.5">
                  <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button type="primary" plain icon="Delete" @click="handleDeleteBatch">删除</el-button>
               </el-col>
               <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
            <el-table v-if="refreshTable" v-loading="loading" :data="menuList" row-key="menuId"
               :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
               @selection-change="handleSelectionChange">
               <el-table-column type="selection" :selectable="selectable" width="55" />
               <el-table-column prop="code" label="编码"></el-table-column>
               <el-table-column prop="name" label="字典名称"></el-table-column>
               <el-table-column prop="mappingCode" label="映射字典编码"></el-table-column>
               <el-table-column label="操作" fixed="right" align="center" width="280" class-name="small-padding fixed-width">
                  <template #default="scope">
                     <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
                     <el-button v-if="scope.row.parentId != 0" link type="primary" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
                  </template>
               </el-table-column>
            </el-table>
            <pagination
               v-show="total > 0"
               :total="total"
               v-model:page="queryParams.pageNum"
               v-model:limit="queryParams.pageSize"
               @pagination="getList"
            />
         </div>
      </div>
      <!-- 添加或修改 -->
      <el-dialog :title="title" v-model="open" width="800px" append-to-body>
         <el-form ref="editRef" :model="form" :rules="rules" label-width="80">
            <el-row :gutter="10">
               <el-col :span="12">
                  <el-form-item label="系统" prop="systemId">
                     <el-select
                        v-model="form.systemId"
                        placeholder="请选择系统"
                        clearable
                        @change="handleSystemChange('edit')">
                        <el-option
                           v-for="system in dataSystemOptions"
                           :key="system.id"
                           :label="system.name"
                           :value="system.id"
                        />
                     </el-select>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="类型" prop="typeId" label-width="120">
                     <el-select v-model="form.typeId" placeholder="选择系统后选择字典类型" clearable>
                        <el-option
                           v-for="type in dialogDictTypeOptions"
                           :key="type.id"
                           :label="type.typeName"
                           :value="type.id"
                        />
                     </el-select>
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="字典编码" prop="code">
                     <el-input v-model="form.code" placeholder="请输入字典编码" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="映射字典编码" prop="mappingCode" label-width="120">
                     <el-input v-model="form.mappingCode" placeholder="请输入映射字典编码" />
                  </el-form-item>
               </el-col>
               <el-col :span="12">
                  <el-form-item label="字典名称" prop="name">
                     <el-input v-model="form.name" placeholder="请输入字典名称" />
                  </el-form-item>
               </el-col>
            </el-row>
         </el-form>
         <template #footer> 
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Menu">
import { ref, watch } from "vue";
import {
   dictGetListByPage,
   dictUpdate,
   dictAdd,
   dictDelete,
   dictGetDetail
} from "@/api/dict";
import { dictTypeGetList } from "@/api/dict/type";
import { dataSystemGetList } from "@/api/dataSystem";

const { proxy } = getCurrentInstance();
const menuList = ref([]);
const open = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(false);
const refreshTable = ref(true);
const total = ref(0);

const data = reactive({
   form: {},
   queryParams: {
      pageNum: 1,
      pageSize: 10,
      keyword: null,
      systemId: null,
   },
   detail: {},
   rules: {
      systemId: [{ required: true, message: "请选择所属系统", trigger: "change" }],
      typeId: [{ required: true, message: "请选择字典类型", trigger: "change" }],
      name: [{ required: true, message: "请输入字典名称", trigger: "change" }],
      code: [{ required: true, message: "字典编码", trigger: "change" }],
      mappingCode: [{ required: true, message: "映射字典编码", trigger: "change" }]
   }
});

const { queryParams, form, detail, rules } = toRefs(data);
/** 查询系统列表 */
function getList() {
   loading.value = true;
   dictGetListByPage(queryParams.value).then(response => {
      menuList.value = response.data.records;
      total.value = response.data.total;
      loading.value = false;
   }).catch(()=>{
      proxy.$modal.msgError("获取列表数据失败");
      loading.value = false;
   });
}

const dataSystemOptions = ref([]);
/** 获取系统选项 */
function getDataSystemOption(type) {
   dataSystemGetList().then(response => {
      dataSystemOptions.value = response.data;
   });
}

// 修改搜索栏系统
function handleSystemChange(type){
   if(type === 'list'){
      queryParams.value.typeId = null;
      getList();
      getDictTypeOption(type)
   }
   if(type === 'edit'){
      form.value.typeId = null;
      getDictTypeOption(type)
   }
}

// 字典类型
const dictTypeOptions = ref([]);
const dialogDictTypeOptions = ref([]);
function getDictTypeOption(type) {
   if(type === 'list'){
      dictTypeOptions.value = [];
      dictTypeGetList({ systemId: queryParams.value.systemId }).then(response => {
         if(response.data?.length){
            dictTypeOptions.value = [
               { id: null, typeName: '全部' },
               ...response.data
            ];
         } else {
            dictTypeOptions.value = [];
         }
      });
   }
   if(type === 'edit'){
      dialogDictTypeOptions.value = [];
      dictTypeGetList({ systemId: form.value.systemId }).then(response => {
         dialogDictTypeOptions.value = response.data;
      });
   }
}

function handleDictTypeClick(value){
   queryParams.value.typeId = value.id;
   getList();
}

/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}

/** 表单重置 */
function reset() {
   form.value = {
      code: null,
      id: null,
      mappingCode: null,
      name: null,
      remark: null,
      systemId: null,
      typeId: null
   };
   detail.value = {};
   editTargetId.value = null;
   proxy.resetForm("editRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
   queryParams.value = {
      pageNum: 1,
      pageSize: 10,
      keyword: null,
      systemId: null
   }  
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
   reset();
   open.value = true;
   getDataSystemOption()
   title.value = "新增字典";
}

const editTargetId = ref(null)
/** 修改按钮操作 */
async function handleUpdate(row) {
   reset();
   editTargetId.value = row.id
   dictGetDetail({id: row.id}).then(response => {
      form.value = {
         ...response.data,
         systemId: Number(response.data.systemId) || null
      };
      open.value = true;
      title.value = "修改字典";
      getDataSystemOption();
      getDictTypeOption('edit');
   });
}

/** 提交按钮 */
function submitForm() {
   proxy.$refs["editRef"].validate(valid => {
      if (valid) {
         if (editTargetId.value) {
            dictUpdate({ ...form.value, id: editTargetId.value}).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               open.value = false;
               editTargetId.value = null;
               getList();
            });
         } else {
            dictAdd(form.value).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               open.value = false;
               getList();
            });
         }
      }
   });
}

/** 删除按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.name + '"的字典?').then(function () {
      return dictDelete({ ids: row.id });
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}

const selectedList = ref([])
function handleSelectionChange(list) {
   selectedList.value = list
}

/** 多选删除操作 */
function handleDeleteBatch() {
   if (selectedList.value.length) {
      proxy.$modal.confirm('是否确认删除选中的' + selectedList.value.length + '个字典?').then(function () {
         const ids = selectedList.value.map(item => item.id).join(',');
         return dictDelete({ ids });
      }).then(() => {
         getList();
         proxy.$modal.msgSuccess("删除成功");
      }).catch(() => { });
   } else {
      proxy.$modal.msgError("请选择要删除的数据");
   }
}

getList();
getDataSystemOption();
</script>
<style lang='scss' scoped>
.tree-title{
   font-weight: bold;
   height: 20px;
   margin-bottom: 5px;
   box-sizing: border-box;
   color: #606266;
   font-size: 14px;
}
:deep(.el-tree){
   width: 250px;
   height: calc(100vh - 250px);
   border-radius: var(--el-border-radius-base);
   overflow-y: overlay;
   border: 1px solid var(--el-border-color);
   margin-right: 10px;
   .el-tree-node.is-current{
      .el-tree-node__content{
         background-color: #cfe5fc;
      }
   }
}
</style>